package com.badibadi.mytools;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

public class CropPictureTools {

	private static final int TAKE_PICTURE = 0;
	private static final int CHOOSE_PICTURE = 1;
	private static final int CROP = 2;
	private static final int CROP_PICTURE = 3;
    private static String CROP_Uri="";
	private static final int SCALE = 5;//照片缩小比例
	public static void showPicturePicker(final Context context,boolean isCrop){
		final boolean crop = isCrop;
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("图片来源");
		builder.setNegativeButton("取消", null);
		builder.setItems(new String[]{"拍照","相册"}, new DialogInterface.OnClickListener() {
			//类型码
			int REQUEST_CODE;
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case TAKE_PICTURE:
					Uri imageUri = null;
					String fileName = null;
					Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					if (crop) {
						REQUEST_CODE = CROP;
						//删除上一次截图的临时文件
						SharedPreferences sharedPreferences = context.getSharedPreferences("temp",Context.MODE_WORLD_WRITEABLE);
						ImageTools.deletePhotoAtPathAndName(Environment.getExternalStorageDirectory().getAbsolutePath(), sharedPreferences.getString("tempName", ""));
						
						//保存本次截图临时文件名字
						fileName = String.valueOf(System.currentTimeMillis()) + ".jpg";
						Editor editor = sharedPreferences.edit();
						editor.putString("tempName", fileName);
						editor.commit();
					}else {
						REQUEST_CODE = TAKE_PICTURE;
						fileName = "image.jpg";
					}
					imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),fileName));
					//指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
					openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
					((Activity)(context)).startActivityForResult(openCameraIntent, REQUEST_CODE);
					break;
					
				case CHOOSE_PICTURE:
					Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
					if (crop) {
						REQUEST_CODE = CROP;
					}else {
						REQUEST_CODE = CHOOSE_PICTURE;
					}
					openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
					((Activity)(context)).startActivityForResult(openAlbumIntent, REQUEST_CODE);
					break;

				default:
					break;
				}
			}
		});
		builder.create().show();
	}
	
	
	/*
	 * 截取图片
	 */
		public static void cropImage(Context context,Uri uri, int outputX, int outputY, int requestCode){
			Intent intent = new Intent("com.android.camera.action.CROP");  
	        intent.setDataAndType(uri, "image/*");
	        intent.putExtra("crop", "true");  
	        intent.putExtra("aspectX", 1);  
	        intent.putExtra("aspectY", 1.5);
	        intent.putExtra("outputX", outputX);   
	        intent.putExtra("outputY", outputY); 
	        intent.putExtra("outputFormat", "JPEG");
	        intent.putExtra("noFaceDetection", true);
	        intent.putExtra("return-data", true);  
	        ((Activity)(context)).startActivityForResult(intent, requestCode);
		}
	
	
		/**
		 * 
		 * @param context
		 * @param requestCode
		 * @param resultCode
		 * @param data
		 */
		public static String getReturnData(Context context,int requestCode,int resultCode,Intent data)
		{
			
			if (resultCode == ((Activity)(context)).RESULT_OK) {
				switch (requestCode) {
				case TAKE_PICTURE:
					//将保存在本地的图片取出并缩小后显示在界面上
					Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/image.jpg");
					Bitmap newBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
					//由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
					bitmap.recycle();
					
					//将处理过的图片显示在界面上，并保存到本地
//					iv_image.setImageBitmap(newBitmap);
//					   
					String value=String.valueOf(System.currentTimeMillis());
					ImageTools.savePhotoToSDCard(newBitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), value);
					
					File photoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() , value + ".png");
//					if(photoFile.is)
					String a=photoFile.getPath();
					String b=photoFile.getAbsolutePath();
//					   
					return a;

				case CHOOSE_PICTURE:
					ContentResolver resolver = context.getContentResolver();
					//照片的原始资源地址
					Uri originalUri = data.getData(); 
					return originalUri.getPath();
//		            try {
//		            	//使用ContentProvider通过URI获取原始图片
//						Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
//						if (photo != null) {
//							//为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
//							Bitmap smallBitmap = ImageTools.zoomBitmap(photo, photo.getWidth() / SCALE, photo.getHeight() / SCALE);
//							//释放原始图片占用的内存，防止out of memory异常发生
//							photo.recycle();
//							   
////							iv_image.setImageBitmap(smallBitmap);
//							
//							
//							
//						}
//					} catch (FileNotFoundException e) {
//					       
//					} catch (IOException e) {
//						   
//					}
//					break;
					
				case CROP:
					Uri uri = null;
					if (data != null) {
						uri = data.getData();
//						   ("Data");
					}else {
//						   ("File");
						String fileName = context.getSharedPreferences("temp",Context.MODE_WORLD_WRITEABLE).getString("tempName", "");
						
						File f=new File(Environment.getExternalStorageDirectory(),fileName);
						uri = Uri.fromFile(f);
					}
					CROP_Uri=uri.getPath();
//					   
					CropPictureTools.cropImage(context, uri, 500, 500, CROP_PICTURE);
//					   
					break;
				
				case CROP_PICTURE:
					Bitmap photo = null;
					Uri photoUri = data.getData();
					
					if (photoUri != null) {
						photo = BitmapFactory.decodeFile(photoUri.getPath());
					}
					if (photo == null) {
						Bundle extra = data.getExtras();
						
						if (extra != null) {
			                photo = (Bitmap)extra.get("data");  
//			                   
			                ByteArrayOutputStream stream = new ByteArrayOutputStream();
			                photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
			            }  
					}
//					fff
					
					
					String uris=CROP_Uri;
					CROP_Uri="";
//					   
					return uris;
//					iv_image.setImageBitmap(photo);
				default:
					break;
				}
			}
			return "";
			
		}
		

		/**
		 * 
		 * @param context
		 * @param requestCode
		 * @param resultCode
		 * @param data
		 */
		public static String getReturnData(Context context,int requestCode,int resultCode,Intent data,int cropWidth,int cropHeight)
		{
			
			if (resultCode == ((Activity)(context)).RESULT_OK) {
				switch (requestCode) {
				case TAKE_PICTURE:
					//将保存在本地的图片取出并缩小后显示在界面上
					Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/image.jpg");
					Bitmap newBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
					//由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
					bitmap.recycle();
					
					//将处理过的图片显示在界面上，并保存到本地
//					iv_image.setImageBitmap(newBitmap);
//					   
					String value=String.valueOf(System.currentTimeMillis());
					ImageTools.savePhotoToSDCard(newBitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), value);
					
					File photoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() , value + ".png");
//					if(photoFile.is)
					String a=photoFile.getPath();
					String b=photoFile.getAbsolutePath();
//					   
					return a;

				case CHOOSE_PICTURE:
					ContentResolver resolver = context.getContentResolver();
					//照片的原始资源地址
					Uri originalUri = data.getData(); 
					return originalUri.getPath();
//		            try {
//		            	//使用ContentProvider通过URI获取原始图片
//						Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
//						if (photo != null) {
//							//为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
//							Bitmap smallBitmap = ImageTools.zoomBitmap(photo, photo.getWidth() / SCALE, photo.getHeight() / SCALE);
//							//释放原始图片占用的内存，防止out of memory异常发生
//							photo.recycle();
//							   
////							iv_image.setImageBitmap(smallBitmap);
//							
//							
//							
//						}
//					} catch (FileNotFoundException e) {
//					       
//					} catch (IOException e) {
//						   
//					}
//					break;
					
				case CROP:
					Uri uri = null;
					if (data != null) {
						uri = data.getData();
//						   ("Data");
					}else {
//						   ("File");
						String fileName = context.getSharedPreferences("temp",Context.MODE_WORLD_WRITEABLE).getString("tempName", "");
						
						File f=new File(Environment.getExternalStorageDirectory(),fileName);
						uri = Uri.fromFile(f);
					}
					CROP_Uri=uri.getPath();
//					   
					CropPictureTools.cropImage(context, uri, cropWidth, cropHeight, CROP_PICTURE);
//					   
					break;
				
				case CROP_PICTURE:
					Bitmap photo = null;
					Uri photoUri = data.getData();
					
					if (photoUri != null) {
						photo = BitmapFactory.decodeFile(photoUri.getPath());
					}
					if (photo == null) {
						Bundle extra = data.getExtras();
						
						if (extra != null) {
			                photo = (Bitmap)extra.get("data");  
//			                   
			                ByteArrayOutputStream stream = new ByteArrayOutputStream();
			                photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
			            }  
					}
//					fff
					
					
					String uris=CROP_Uri;
					CROP_Uri="";
//					   
					return uris;
//					iv_image.setImageBitmap(photo);
				default:
					break;
				}
			}
			return "";
			
		}
		
		public static String getStringUri(Context context,String myImageUrl)
		{
//			string  myImageUrl = "content://media/external/images/media/***";
		     Uri uri = Uri.parse(myImageUrl);
		     
		 
		     String[] proj = { MediaStore.Images.Media.DATA };   
		     Cursor actualimagecursor = ((Activity) context).managedQuery(uri,proj,null,null,null);  
		     int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);   
		     actualimagecursor.moveToFirst();   
		     
		 
		     String img_path = actualimagecursor.getString(actual_image_column_index);  
		     File file = new File(img_path);
		     Uri fileUri = Uri.fromFile(file);
		     return fileUri.getPath();
		}
		
		public static String getStringUri2(Context context,String picPath){
			
			
			Uri mUri = Uri.parse("content://media/external/images/media"); 
            Uri mImageUri = null;

            Cursor cursor = ((Activity) context).managedQuery(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null,
                    null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
            cursor.moveToFirst();

            while (!cursor.isAfterLast()) {
                String data = cursor.getString(cursor
                        .getColumnIndex(MediaStore.MediaColumns.DATA));
                if (picPath.equals(data)) {
                    int ringtoneID = cursor.getInt(cursor
                            .getColumnIndex(MediaStore.MediaColumns._ID));
                    mImageUri = Uri.withAppendedPath(mUri, ""
                            + ringtoneID);
                   return mImageUri.toString();
                }
                cursor.moveToNext();
            }
			return "";
		};
		
}
